package cc.sheji.controller;


import cc.sheji.config.DeviceConfig;
import cc.sheji.domain.Job;
import cc.sheji.domain.JsonResult;
import cc.sheji.domain.TestData;
import cc.sheji.exception.TooMoreActionException;
import cc.sheji.reposity.JobRepository;
import cc.sheji.util.HttpUtil;
import cn.dev33.satoken.stp.StpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static org.springframework.data.jpa.domain.AbstractPersistable_.id;

@Validated
@RestController
@RequestMapping(value = "/api/v1/test")
public class TestController {

    @Autowired
    JobRepository jobRepository;

    @Autowired
    DeviceConfig deviceConfig;

    @Autowired
    HttpUtil httpUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    boolean debug1 = true;
    boolean debug1_1 = true;
    boolean debug1_0;
    //control out error debug
    boolean debug1_99 = true;
    boolean debug2 = false;

    public void doQuery(ArrayList<Map> reList) {

        if (debug2) {
            System.out.println("new do query-------------------------" + new Date());
            System.out.println("do query-------------------------");
            System.out.println("do query-------------------------");
            System.out.println("reList:" + reList);
        }

        if (reList == null || reList.size() == 0)
            return;

        String cookie = deviceConfig.cookie;
        String getImgUrl = deviceConfig.plateUrl;
        List<Job> allJob = jobRepository.findAllByStateAndPlateUserId(1, "" + reList.get(0).get("id1"));

        Map<String, ArrayList<Map<String, Object>>> midDateMap = new HashMap<>();

        if (allJob.size() > 0) {

            if (debug2) {
                System.out.println("alljob:" + allJob);
            }

            try {

                final int startSie = reList.size() - 1;
                System.out.println("reListSize:" + reList.size());
                for (int i = 0; i < reList.size(); i++) {


                    System.out.println("task:" + i);
                    Map<String, Object> mapOrigin = reList.get(i);
                    Object id = mapOrigin.get("id");

                    String keyId = "taskId" + id;
                    if (redisTemplate.hasKey(keyId)) {
                        System.out.println("have "+keyId);
                        continue;
                    }

                    List<String> olist = (List<String>) mapOrigin.get("olist");
                    Object text = mapOrigin.get("text");
                    String cmdName = "";
                    if (text != null) {
                        cmdName = "" + text;
                    }
                    cmdName = cmdName.replaceAll(" ", "");
                    cmdName = cmdName.replaceAll("-", "");
                    cmdName = cmdName.replaceAll("_", "");
                    ArrayList<Map<String, Object>> maps = midDateMap.get(cmdName);
                    if (maps == null) {
                        maps = new ArrayList<>();
                        midDateMap.put(cmdName, maps);
                    }
                    maps.add(mapOrigin);
                    for (String url1 : olist) {
                        try {
                            if (url1 == null)
                                continue;
                            String key = "image" + url1;
                            if (redisTemplate.hasKey(key)) {
                                continue;
                            }
                            String url = httpUtil.getLocation(url1);
                            Thread.sleep(300);
                            if (url != null) {
                                redisTemplate.opsForValue().set(key, url, 20, TimeUnit.DAYS);
                            }
                        } catch (Exception e) {
                            System.out.println("net error");
                            e.printStackTrace();
                        }
                    }
                }

                System.out.println("mid：" + midDateMap);
                System.out.println("mid1：" + midDateMap.keySet());


                for (int k = 0; k < allJob.size(); k++) {
                    try {

                        Job job = allJob.get(k);
                        String fullTextCmd = job.getFullTextCmd();
                        job.getFullTextCmd();
                        String cmd = "";
                        if (fullTextCmd != null) {
                            cmd = fullTextCmd.trim().replaceAll("  ", "");
                        }
                        cmd = cmd.trim();
                        cmd = cmd.replaceAll(" ", "");
                        cmd = cmd.replaceAll("-", "");
                        cmd = cmd.replaceAll("_", "");
                        ArrayList<Map<String, Object>> OringinList = midDateMap.get(cmd);
                        System.out.println("keys:" + midDateMap.keySet());
                        System.out.println("keycmd:" + cmd);
                        if (OringinList == null) {
                            System.out.println("not find json object");
                            continue;
                        }
//                        System.out.println("job text:" + cmd);
                        ArrayList resultImagelist = new ArrayList();
                        System.out.println("---------start----------");
                        for (int i = 0; i < OringinList.size(); i++) {
                            Map<String, Object> stringObjectMap = OringinList.get(i);

                            System.out.println(stringObjectMap);
                            try {
                                List<String> list1 = (List<String>) stringObjectMap.get("olist");
                                boolean match = true;
                                Integer have = 0;
                                for (String url : list1) {
                                    String key = "image" + url;
//                                    System.out.println("match oringin url:"+url);
                                    String rUrl = (String) redisTemplate.opsForValue().get(key);


                                    if (rUrl == null || url == null || url.isEmpty() || rUrl.toLowerCase().equals("null") || url.equals("null"))
                                        continue;

                                    String attachment = "" + job.getAttachment();
                                    System.out.println("attach:" + attachment);
                                    System.out.println("rUrl:" + rUrl);
                                    url = "" + rUrl;
                                    attachment = attachment.replace(":443", "");
                                    url = url.replace(":443", "");
                                    if (!attachment.contains(url)) {
                                        match = false;
                                    } else {
                                        System.out.println("match attach1:"+attachment);
                                        System.out.println("match url:"+url);
                                        have++;
                                    }
                                }
                                Integer taskType = job.getTaskType();


                                String cmdName = "";
                                Object cmd1 = stringObjectMap.get("text");
                                if (cmd1 != null) {
                                    cmdName = "" + cmd1;
                                }
                                cmdName = cmdName.replaceAll(" ", "");
                                cmdName = cmdName.replaceAll("-", "");
                                cmdName = cmdName.replaceAll("_", "");
                                System.out.println("cmdName:" + cmdName);
                                System.out.println("cmd:" + cmd);

                                System.out.println("have:" + have);
                                int iamgeSize = 0;
                                for (int ll = 0; ll < job.getAttachImages().length; ll++) {
                                    String attachImage = job.getAttachImages()[ll];
                                    System.out.println("imageAtta:" + attachImage);
                                    if (attachImage != null && attachImage.length() > 6) {
                                        iamgeSize++;
                                    }
                                }
                                System.out.println("attchSize:" + job.getAttachImages().length);


                                System.out.println("have:" + have);

                                String badContent = (String) stringObjectMap.get("badContent");
                                badContent = badContent.toLowerCase().replaceAll(" ", "");

                                String badContentFullText = job.getBadContentFullText();
                                badContentFullText = badContentFullText.replaceAll(" ", "").toLowerCase();

                                if (badContentFullText == null || badContentFullText.equals("null"))
                                    badContentFullText = "";

                                if (badContent == null || badContent.equals("null"))
                                    badContent = "";

                                System.out.println("badContentFullText：" + badContentFullText);
                                System.out.println("badContent：" + badContent);
                                if (!badContentFullText.equals(badContent))
                                    match = false;


                                if (taskType == 3) {
                                    boolean isVariation = (boolean) stringObjectMap.get("isVariation");
                                    if (!isVariation) {
                                        match = false;
                                    }
                                }

                                if (taskType == 2) {
                                    boolean isUpScale = (boolean) stringObjectMap.get("isUpScale");
                                    if (!isUpScale) {
                                        match = false;
                                    }
                                }

                                if(taskType==1){
                                    boolean isVariation = (boolean) stringObjectMap.get("isVariation");
                                    if (isVariation) {
                                        match = false;
                                    }
                                    boolean isUpScale = (boolean) stringObjectMap.get("isUpScale");
                                    if (isUpScale) {
                                        match = false;
                                    }
                                }
                                cmd=cmd.replace("tile","");
                                cmd=cmd.replace(" ","");
                                cmdName=cmdName.replace("tile","");
                                cmdName=cmdName.replace(" ","");

                                if (match && cmdName.trim().equals(cmd) && have == iamgeSize) {
                                    System.out.println("havelll:" + have);

                                    List<String> imagePaths = new ArrayList<>();
                                    String finalImage = "" + stringObjectMap.get("finalImage");
                                    System.out.println("haveImage:" + finalImage);
                                    resultImagelist.add(finalImage);
                                    job.setResultImages(imagePaths);
                                    if (finalImage == null || finalImage.length() < 50) {
                                        continue;
                                    }
                                    String reId = finalImage.substring(finalImage.length() - 40, finalImage.length() - 4);

                                    job.setTaskRelationId("" + reId);
                                    job.setPlatformMessageId("" + stringObjectMap.get("messageId"));
                                    job.setState(2);
                                    job.setResultImages(resultImagelist);
                                    job.setPlateId("" + stringObjectMap.get("messageId"));
                                    if (!resultImagelist.isEmpty()) {
                                        try {
                                            jobRepository.save(job);
                                            String keyId = "taskId" + stringObjectMap.get("id");
                                            redisTemplate.opsForValue().set(keyId, new Date(), 20, TimeUnit.DAYS);

                                        } catch (Throwable throwable) {
                                            throwable.printStackTrace();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                        System.out.println("---------end----------");
                    } catch (Exception e) {
                        System.out.println("处理mid 失败");
                        e.printStackTrace();
                    }

                }

            } catch (Throwable e) {
                System.out.println("请求mid出错了");
                e.printStackTrace();
            }


        }

    }


    @RequestMapping()
    public JsonResult get(@RequestBody TestData testData) {

        System.out.println("new updata row------------------------------------------" + new Date());
        if (debug1_1) {
            System.out.println("---------------------------------------------------------------------------------------------------------------");
            System.out.println("---------------------------------------------------------------------------------------------------------------");
            System.out.println("---------------------------------------------------------------------------------------------------------------");
            System.out.println("---------------------------------------------------------------------------------------------------------------");
        }
        ArrayList<Map> reList = new ArrayList<>();
        String html = testData.getData();
        System.out.println("data:"+html);
        Document document = Jsoup.parse(html);
        Elements elementsByClass = document.getElementsByClass("scrollerContent_c73942");
          System.out.println(elementsByClass);
        int scrollerInnerNum = 0;
        for (Element element : elementsByClass) {
            if (debug1_1) {
                System.out.println("line:***************************************" + (++scrollerInnerNum));
                System.out.println(element);
            }
            Elements lis = element.getElementsByTag("li");
            int lisSize = 0;
            for (int i = lis.size() - 1; i >0 && i > 0; i--) {
                String cmdFinal = "";
                String imageFinal = "";
                String badContent = "";
                boolean isUpScale = false;
                boolean isVariation = false;
                Element element1 = lis.get(i);
                String id = element1.attr("id");
                ArrayList<String> oList = new ArrayList<>();
                if (debug1) {

                   // System.out.println("line%%%%%%%%%%%%%%%%%%%%%%%num:" + (++lisSize) + "%%%%%%oline:" + i);
                    if (i == lis.size() - 1) {
//                        System.out.println("line%%%%%%%%%%%%%%%%%%%%%%%");
//                        System.out.println("line%%%%%%%%%%%%%%%%%%%%%%%");
//                        System.out.println("line%%%%%%%%%%%%%%%%%%%%%%%");
//                        System.out.println("line%%%%%%%%%%%%%%%%%%%%%%%");
//                        System.out.println("line%%%%%%%%%%%%%%%%%%%%%%%");
//                        System.out.println("line%%%%%%%%%%%%%%%%%%%%%%%");
                    }
                  //  System.out.println(element1);
//                    System.out.println("text%%%%%%%%%%%%%%%%%%%%%%%");
                    String text = element1.text();
                    System.out.println(text);
                    if(!text.contains("U1 U2 U3 U4 V1 V2 V3 V4")){
                        isUpScale=true;
                    }
                }
                Elements elementsByClass1 = element1.getElementsByClass("originalLink__94d5d");
                Elements textElements = element1.getElementsByClass("markup_a7e664");
                if (debug1){
//                    System.out.println("originalLinkSize:" + elementsByClass1.size());
                }

                for (int mm = 0; mm < elementsByClass1.size(); mm++) {
                    String href = elementsByClass1.get(mm).attr("href");
//                    if (href == null || href.length() < 6 || href.endsWith("grid_0.webp")) {
//                        continue;
//                    }
                    if (href == null || href.length() < 6 ) {
                        continue;
                    }
                    if(href.contains("?")){
                        href=href.substring(0,href.indexOf("?"));
                    }

                    if (!href.endsWith("png"))
                        continue;
                    imageFinal = href;
//                    if (debug1)
//                        System.out.println("href" + mm + ":" + href);
                }

                if (imageFinal == null || imageFinal.length() < 6) {
                    continue;
                }

                if (debug1) {
//                    System.out.println("inputElementSize:" + textElements.size());
                }

                for (int mm = 0; mm < textElements.size(); mm++) {

                    Element element2 = textElements.get(mm);
                    Elements as = element2.getElementsByTag("a");
                    if (debug1) {
//                        System.out.println("inputElement%%%%%%%%%%%%%%%%%%%%%%%" + mm);
//                        System.out.println("input iamge size:" + as.size());
                    }
                    for (int n = 0; n < as.size(); n++) {
                        Element element3 = as.get(n);
                        String href = element3.attr("href");
                        if (href != null && href.length() > 6)
                            oList.add(href);
                    }
                    Elements children = element2.children();
                    for (int k = 0; k < children.size(); k++) {
                        Element element3 = children.get(k);
                        if (element3.text().contains("- Image")) {
                            isUpScale = true;
                            if (debug1) {
                               // System.out.println("is upscaled element");
                            }
                        }
                        if (element3.text().contains("Variations by")) {
                            isVariation = true;
                            if (debug1){
                                System.out.println("isVariations by");
                            }

                        }
//                        if (debug1)
//                            System.out.println("intput element item:" + element3);
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    Elements strong = element2.getElementsByTag("strong");
                    if (strong.size() > 0) {
                        Element element3 = strong.get(0);
                        Elements spans = element3.getElementsByTag("span");
                        String text1 = element3.text();
                        int indexNo = text1.indexOf("--no");
                        int indexV = text1.indexOf("--v");

                        if (indexNo > 0 && indexV > 0) {
                            badContent = text1.substring(indexNo + 5, indexV - 1);
                            badContent = badContent.trim();
                        }
                        if (debug1)
                            System.out.println("input strong:" + element3.text());
                        for (int m = 0; m < spans.size(); m++) {

                            Element element4 = spans.get(m);
                            String text = element4.text();
                            if (text.equals("-")) {
                                break;
                            }
                            if (!text.contains("https://s.mj.run") && !text.isEmpty()) {
                                text = text.trim();
                                stringBuilder.append(text + " ");
                            }
                        }

                    }
                    cmdFinal = stringBuilder.toString().trim();

                }
                if (badContent == null)
                    badContent = "";

                Map<String, Object> map = new HashMap<>();
                String[] split = id.split("-");
                if (split.length == 4) {
                    map.put("id1", split[2]);
                    map.put("messageId", split[3]);
                }
                if (badContent == null)
                    badContent = "";
                map.put("finalImage", imageFinal);
                map.put("olist", oList);
                map.put("text", cmdFinal);
                map.put("id", id);
                map.put("isUpScale", isUpScale);
                map.put("isVariation", isVariation);
                map.put("badContent", badContent);
                reList.add(map);
                if (debug1 || debug1_99) {
                    System.out.println("id:" + id);
                    System.out.println("finalImage:" + imageFinal);
                    System.out.println("finalCmd:" + cmdFinal);
                    System.out.println("olist:" + oList);
                    System.out.println("badContent:" + badContent);
                    System.out.println("isVariation:" + isVariation);
                    System.out.println("isUpScale:" + isUpScale);
                    System.out.println("end line%%%%%%%%%%%%%%%%%%%%%%%");
                    System.out.println();

                    if (debug1_99) {

                        System.err.println("id:" + id);
//                            System.err.println("finalImage:" + imageFinal);
//                            System.err.println("isUpScale:" + isUpScale);
                    }

                }


            }
        }
        System.out.println("end new updata row------------------------------------------" + new Date());
        new Thread() {
            @Override
            public void run() {
                doQuery(reList);
            }
        }.start();

        return JsonResult.Success();
    }

}
